<template>
  <Temp title="图例">
    <div class="legend">
      <el-select
        :popper-append-to-body="true"
        popper-class="legend-layer"
        v-model="selectedLayer"
        filterable
        placeholder="请选择"
        size="small"
        @visible-change="onSelectVisibleChange"
      >
        <el-option
          v-for="item in loadedLayers"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <el-scrollbar>
        <div class="legend-list" v-if="selectedLayer">
          <div
            v-for="item in legendData[selectedLayer]"
            :key="item.name"
            class="legend-list-item"
          >
            <el-image :src="item.img" />
            <span>{{ item.name }}</span>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </Temp>
</template>

<script>
import axios from 'axios'
import Temp from '@/components/utool/components/temp'
import { getAction } from '@/utils/helper'

const mapViewer = {}
const _layerManager = {}

export default {
  name: 'Legend',
  // inject: ['viewerId'],
  components: {
    Temp
  },
  props: ['viewerId'],
  data() {
    return {
      loadedLayers: [],
      selectedLayer: '',
      legendData: {}
    }
  },
  async created() {
    const { toolManager, layerManager } = await getAction(
      this.viewerId
    )
    mapViewer[this.viewerId] = toolManager.viewer
    _layerManager[this.viewerId] = layerManager

    this.$bus.$on('removeAdd', () => {
      this.getLayers(true)
    })
    this.$bus.$on('removeLayer', () => {
      this.getLayers(true)
    })

    this.getLayers()
  },
  methods: {
    getLayers(chooseFirst) {
      const layerList = _layerManager[this.viewerId].layers
        .reverse()
        .filter((item) => item.type !== 'layer')
      // console.log('图层', layerList)
      this.loadedLayers.splice(0, this.loadedLayers.length)
      this.loadedLayers.push(
        ...layerList.map((item) => {
          return {
            label: item.title,
            value: item.id,
            data: item
          }
        })
      )
      if (chooseFirst) {
        if (this.loadedLayers.length > 0) {
          this.selectedLayer =
            this.loadedLayers[0] &&
            this.loadedLayers[0].value
        } else {
          this.selectedLayer = ''
        }
      } else {
        if (
          this.loadedLayers.every(
            (item) => item.value !== this.selectedLayer
          )
        ) {
          // 已选择的图层被移除
          this.selectedLayer =
            this.loadedLayers[0] &&
            this.loadedLayers[0].value
        }
      }
    },
    getLayerLegendData(layer) {
      console.log('layer', layer)
      this.legendData[layer.id] = []
      axios
        .get(layer.serviceUrl + '/layers.json')
        .then((res) => {
          if (res.data) {
            const subLayerNames = []
            res.data[0].subLayers.layers.forEach(
              (subLayer) => {
                subLayerNames.push(
                  subLayer.name + '@@' + res.data[0].name
                )
              }
            )
            console.log('subLayerNames', subLayerNames)
            subLayerNames.forEach((subLayerName) => {
              axios
                .get(
                  layer.serviceUrl +
                    '/layers/' +
                    subLayerName +
                    '.json'
                )
                .then((res) => {
                  if (
                    res.data &&
                    res.data.theme &&
                    res.data.theme.items &&
                    res.data.theme.items instanceof Array &&
                    res.data.theme.items.length
                  ) {
                    console.log(
                      'res.data.theme.items',
                      res.data.theme.items
                    )
                    res.data.theme.items.forEach(
                      (item, index) => {
                        this.legendData[layer.id].push({
                          name: item.caption,
                          img:
                            layer.serviceUrl +
                            '/layers/' +
                            subLayerName +
                            `/items/${index}/legend.png?width=30&height=30`
                        })
                      }
                    )
                    this.$forceUpdate()
                  }
                })
            })
          }
        })
        .catch((err) => {
          console.error('查询子图层失败', err)
        })
    },
    onSelectVisibleChange(val) {
      if (val) {
        this.getLayers()
      }
    }
  },
  watch: {
    selectedLayer: {
      handler(val, oldVal) {
        if (val) {
          const find = this.loadedLayers.find(
            (item) => item.value === this.selectedLayer
          )
          if (find) {
            this.getLayerLegendData(find.data)
          }
        } else {
          console.log('clear legend')
          if (oldVal) {
            this.legendData[oldVal] = []
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.legend {
  height: 200px;
  width: 200px;
  padding: 10px;
  background-color: #193b51;
  border-radius: 0 0 8px 8px;
  display: flex;
  flex-direction: column;

  ::v-deep {
    .el-scrollbar {
      flex: 1;

      &__wrap {
        overflow-x: hidden;
      }
    }
  }

  &-list {
    margin-top: 10px;
    display: flex;
    flex-direction: column;

    &-item {
      display: flex;
      align-items: center;

      .el-image {
        width: 20px;
        height: 20px;
        margin-right: 6px;
      }

      span {
        font-size: 12px;
        color: #d2e6f0;
      }
    }

    &-item:not(:last-of-type) {
      margin-bottom: 15px;
    }
  }
}

::v-deep {
  .el-input__inner {
    background: rgba(65, 89, 117, 0.5) !important;
    border-color: #4a627f !important;
    height: 30px !important;
    color: #a7beca !important;
  }
}
</style>
